package conv

import (
	"encoding/json"
	"reflect"
	"strconv"
)

// Strval 获取变量的字符串值
// 浮点型 3.0将会转换成字符串3, "3"
// 非数值或字符类型的变量将会被转换成JSON格式字符串
func StrTo(value interface{}) string {
	var key string
	if value == nil {
		return key
	}
	vt := reflect.TypeOf(value)
	v := vt.Kind()

	switch v {
	case reflect.Float64:
		ft := value.(float64)
		key = strconv.FormatFloat(ft, 'f', -1, 64)
	case reflect.Float32:
		ft := value.(float32)
		key = strconv.FormatFloat(float64(ft), 'f', -1, 64)
	case reflect.Int:
		it := value.(int)
		key = strconv.Itoa(it)
	case reflect.Uint:
		it := value.(uint)
		key = strconv.Itoa(int(it))
	case reflect.Int8:
		it := value.(int8)
		key = strconv.Itoa(int(it))
	case reflect.Uint8:
		it := value.(uint8)
		key = strconv.Itoa(int(it))
	case reflect.Int16:
		it := value.(int16)
		key = strconv.Itoa(int(it))
	case reflect.Uint16:
		it := value.(uint16)
		key = strconv.Itoa(int(it))
	case reflect.Int32:
		it := value.(int32)
		key = strconv.Itoa(int(it))
	case reflect.Uint32:
		it := value.(uint32)
		key = strconv.Itoa(int(it))
	case reflect.Int64:
		it := value.(int64)
		key = strconv.FormatInt(it, 10)
	case reflect.Uint64:
		it := value.(uint64)
		key = strconv.FormatUint(it, 10)
	case reflect.String:
		key = value.(string)
	default:
		newValue, _ := json.Marshal(value)
		key = string(newValue)
	}

	return key
}
